<?php
namespace App\Repositories;

use App\Models\BroadCast;
use Carbon\Carbon;

class BroadCastRepository
{
    //获取所有广播
    public function getBroadCasts()
    {
        return BroadCast::orderBy('id', 'desc')->get();
    }

    public function getBroadCast($id)
    {
        $obj = BroadCast::find($id);

        $hours = floor($obj->start_time / 60);
        $minutes = floor($obj->start_time % 60);

        $today = Carbon::createFromTime($hours, $minutes);
        $obj->start_time = $today->toTimeString();
        $obj->last_time = round($obj->last_time / 60, 2);
        return $obj;

    }

    //添加广播
    public function addBroadCast($request)
    {
        //处理时间,转换为相对0点的偏移量,以分钟为单位
        //我也不想这样搞,服务端那边这样搞的
        $start_time = strtotime($request->start_time);
        $diff = $start_time - strtotime(date('Y-m-d'));
        $start_time = floor(abs($diff) / 60);

        $broadcast = BroadCast::create([
            'sender'        => session('admin')->user_name,
            'start_time'    => $start_time,
            'last_time'     => $request->last_time * 60,
            'repeat_times'  => $request->repeat_times,
            'interval_time' => $request->interval_time,
            'enable'        => $request->enable,
            'content'       => $request->content
        ]);

        return $broadcast;
    }

    //更新
    public function updateBroadCast($request, $id)
    {
        $obj = BroadCast::findOrFail($id);

        //可通过访问器优化代码
        $start_time = strtotime($request->start_time);
        $diff = $start_time - strtotime(date('Y-m-d'));
        $start_time = floor(abs($diff) / 60);

        $obj->sender        = session('admin')->user_name;
        $obj->start_time    = $start_time;
        $obj->last_time     = $request->last_time * 60;
        $obj->repeat_times  = $request->repeat_times;
        $obj->interval_time = $request->interval_time;
        $obj->enable        = $request->enable;
        $obj->content       = $request->content;

        $obj->save();
        return true;

    }

    //删除
    public function deleteBroadCast($id)
    {
        return BroadCast::destroy($id);
    }

    //批量删除
    public function destroyList($ids)
    {
        return BroadCast::destroy($ids);
    }
}